package com.boot2523.myrabbitmq.q4;

import com.rabbitmq.client.*;

import java.io.IOException;

public class ConsumerError {
    private static final String EXCHANGE_NAME = "direct_logs";
    private static final String ROUTING_KEY = "error";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 声明 exchange
//        声明一个名为 EXCHANGE_NAME 的 direct 类型的交换机。
//        这是 RabbitMQ 中实现精确路由消息的核心机制，适用于“点对点”或“按键转发”的消息分发场景。
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");

        // 创建临时队列
        String queueName = channel.queueDeclare().getQueue();

        // 将队列绑定到 exchange，指定 routingKey
        channel.queueBind(queueName, EXCHANGE_NAME, ROUTING_KEY);

        System.out.println(" [*] Consumer Error waiting for messages with routing key: " + ROUTING_KEY);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [ERROR] Received: " + message);
        };

        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
    }
}
